<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/27 0027
 * Time: 10:03
 */

namespace app\api\controller;
use app\admin\controller\GroupInvoice;
use app\admin\model\OrderInvoice;
use app\common\model\User;
use app\common\controller\Api;
use app\common\model\UserGroup;
use app\common\model\UserRechargeLog;
use app\common\model\WorkOrder;
use think\Db;

/**
 * 支付相关
 */
class Pays extends Api
{



    public function _initialize()
    {
        parent::_initialize();
    }
    //购买商品回调
    public function goods_response($type = 'alipay'){
        /*$data    = file_get_contents('php://input');
        $data = $this->xml_to_data($data);
        file_put_contents('111.txt', $data['out_trade_no']);*/
        $flag  = false;
        if($type == 'alipay'){
            $flag = true;
            //$data['out_trade_no'] = 'GJ5117800360126';
            if($flag){
                //验签成功
                $order_sn = $_POST['out_trade_no'];
            }else{
                //验签失败
                die('验签失败');
            }
        }else{
            //微信回调
            $data    = file_get_contents('php://input');
            $data = $this->xml_to_data($data);
            // sign不参与签名算法
            $data_sign = $data['sign'];
            unset($data['sign']);
            //$data['out_trade_no'] = 'I812085022861713';
            $key = '171f0f636d1a95185146e00980c5dd21';
            $sign = $this->makeSign($data,$key);
            if (($sign===$data_sign) && ($data['return_code']=='SUCCESS') && ($data['result_code']=='SUCCESS')) {
                $flag = true;
                $order_sn = $data['out_trade_no'];
            }
        }
        /*$flag = true;
        $order_sn = 'A5068253225197';*/
        if($flag){
            //查看订单是否存在
            $order_info = Db::name('order')->where('order_sn',$order_sn)->find();
            if($order_info){
                //如果订单存在查看是否已经支付
                if($order_info['status'] == 0){
                    //用户信息
                    $user = User::where('id',$order_info['userid'])->find();
                    Db::startTrans();
                    try {
                        $res = Db::name('order')->where('order_sn',$order_sn)->where('status',0)->update(['status'=>1,'paytime'=>time()]);
                        if($res){
                            //直推奖
                            direct_push_reward($order_info['actual_price'],$order_info['userid'],$order_info['id']);
                            //间推奖
                            indirect_reward($order_info['actual_price'],$order_info['userid'],$order_info['id']);
                            //级差奖
                            difference_reward($order_info['actual_price'],$order_info['userid'],$order_info['id']);
                            //计算会员是否达到升级要求，如果足够就升级
                            check_parent_level($order_info['userid']);
                        }
                        Db::commit();
                    } catch (ValidateException $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    } catch (PDOException $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    } catch (Exception $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    }
                    if($res){
                        return 'SUCCESS';
                    }
                }
            }
        }else{
            return false;
        }
    }
    public function xml_to_data($xml){
        if(!$xml){
            return false;
        }
        //将XML转为array
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $data;
    }
    /**

     * 生成签名

     * @return 签名，本函数不覆盖sign成员变量

     */
    protected function makeSign($data,$key){
        //获取微信支付秘钥
        //require_once "wxpay/lib/WxPay.Api.php";
        //$key = 'u74B0SejpLomESBIFY3A1pp6Ss36rURI';
        // 去空
        $data=array_filter($data);
        //签名步骤一：按字典序排序参数
        ksort($data);
        $string_a=http_build_query($data);
        $string_a=urldecode($string_a);
        //签名步骤二：在string后加入KEY
        //$config=$this->config;
        $string_sign_temp=$string_a."&key=".$key;
        //签名步骤三：MD5加密
        $sign = md5($string_sign_temp);
        // 签名步骤四：所有字符转为大写
        $result=strtoupper($sign);
        return $result;
    }
}